import React from "react"
import Taro from "@tarojs/taro"
import { Sticky } from "@taroify/core"
import { ArrowRight } from "@taroify/icons"
import GpContainer from "@/components/GpContainer"
import { ScrollView, Text, Navigator, Image, View } from "@tarojs/components"
import GpJumpNavs from "@/components/GpJumpNavs"
import GpCurrentPort from "@/components/GpCurrentPort"
import GpTabbar from "@/components/GpTabbar"
import clsx from "clsx"
import { pageMapper, PagePath } from "@/constants/pageMap"
import { makePagePath, navigation } from "@/utils/router"
import { cloneDeep } from "@/utils/common"
import { getExamColumn } from "@/apis/index"
import styles from "./index.module.scss"

const ports = [{ text: "艺考专题" }]
const arrowSize = Taro.pxTransform(24)
enum ITabSwitchKey {
  /** 艺考百科 */
  wiki = 0,
  /** 专题文章 */
  article = 1
}
type ITabSwitch = {
  text: string
  value: ITabSwitchKey
  link: PagePath
}
const tabSwitchMap: ITabSwitch[] = [
  { text: "艺考百科", value: ITabSwitchKey.wiki, link: pageMapper.column },
  { text: "专题文章", value: ITabSwitchKey.article, link: pageMapper.columnArticle }
]
const selectorPrefix = "sel_"
type IWikiScroll = {
  text: string
  selector: string
  scrollTop: number
}
type IState = {
  curTabSwitch: ITabSwitchKey
  tabSwitches: ITabSwitch[]
  curWikiScroll: string
  wikiScrolls: IWikiScroll[]
  content: IApiRelative.IGetExamColumn.IContent[]
}
/** 艺考专题 */
class ColumnPage extends React.Component<unknown, IState> {
  constructor(props) {
    super(props)
    this.state = {
      curTabSwitch: ITabSwitchKey.wiki,
      tabSwitches: tabSwitchMap,
      curWikiScroll: "",
      wikiScrolls: [],
      content: []
    }
  }
  onReady() {
    this.getColumnData()
  }
  flushScrollTop = () => {
    const wikiScrolls = cloneDeep(this.state.wikiScrolls)
    const query = Taro.createSelectorQuery()
    console.log("wikiScrollsleng", wikiScrolls.length)
    for (let i = 0; i < wikiScrolls.length; i++) {
      query.select("#" + wikiScrolls[i].selector).boundingClientRect()
    }
    query.exec(res => {
      console.log("flushScrollTop", res)
      for (let i = 0; i < res.length; i++) {
        wikiScrolls[i].scrollTop = res[i].top
      }
      this.setState({
        wikiScrolls
      })
      console.log("wikiScrolls---", wikiScrolls)
    })
  }
  onPageScroll(options: Taro.PageScrollObject) {
    const { scrollTop } = options
    const { wikiScrolls } = this.state
    let curSelect: any = null
    // wikiScrolls中的scrollTop理论上是从小到大的, 但是比较需要从大往小比
    for (let i = wikiScrolls.length - 1; i >= 0; i--) {
      const cur = wikiScrolls[i]
      if (scrollTop >= cur.scrollTop) {
        curSelect = cur.selector
        break
      }
    }
    if (curSelect !== null) {
      this.setState({
        curWikiScroll: curSelect
      })
    }
  }
  getSelector = (key: number) => {
    return selectorPrefix + key
  }
  getColumnData = () => {
    Taro.showLoading()
    getExamColumn()
      .then(res => {
        if (res.data.success) {
          const retData = res.data.data
          let curWikiScroll = ""
          const _wikiScrolls: IWikiScroll[] = (retData.menus || []).map(l => {
            if (l.selected) {
              curWikiScroll = this.getSelector(l.id)
            }
            return {
              text: l.name,
              selector: this.getSelector(l.id),
              scrollTop: 0
            }
          })
          // fallback
          if (curWikiScroll === "" && _wikiScrolls.length > 0) {
            curWikiScroll = _wikiScrolls[0].selector
          }
          const _content = retData.content || []
          _content.forEach(l => {
            l.selector = this.getSelector(l.menuId)
            if (l.childs) {
              l.childs.forEach(child => {
                child.url = makePagePath(pageMapper.knownDetail, { id: child.id })
              })
            }
          })
          this.setState(
            {
              wikiScrolls: _wikiScrolls,
              curWikiScroll,
              content: _content
            },
            () => {
              Taro.nextTick(() => {
                this.flushScrollTop()
              })
            }
          )
        }
      })
      .finally(() => {
        Taro.hideLoading()
      })
  }
  /** 快捷导航 */
  renderJumpNavs = () => {
    return (
      <View className="mt-20px">
        <GpJumpNavs />
      </View>
    )
  }
  /** 顶部背景图 */
  renderBanner = () => {
    return (
      <View className="h-200px box-border w-750px relative">
        <Image
          src="https://static.91goodschool.com/UpFiles/public/yikao/image/yikaobg.png"
          className="h-200px w-750px cover-image"
        />
        <View className={clsx("cover-image", styles["banner-bg-mask"])}></View>
        <View className="yehei font-normal text-36px text-hex-fff text-center pt-37px relative z-2">
          艺考知识专题
        </View>
        <View className={clsx(styles["banner-subtitle"], "mt-25px relative z-2")}>
          精选热门艺考百科以及专题文章，为你专业解读
        </View>
        <View className={clsx(styles["banner-subtitle"], "mt-8px relative z-2")}>
          升学经验一网打尽
        </View>
      </View>
    )
  }
  handleTahSwitch = (item: ITabSwitch) => {
    if (this.state.curTabSwitch === item.value) return
    navigation(item.link, null)
  }
  /** tab切换 */
  renderTabSwitch = () => {
    const { tabSwitches, curTabSwitch } = this.state
    const len = tabSwitches.length
    return (
      <View className="flex flex-row justify-center h-90px box-border bg-hex-fff">
        {tabSwitches.map((l, index) => (
          <View
            key={l.value}
            className={clsx(styles["tab-item"], {
              [styles["active"]]: curTabSwitch === l.value,
              "mr-150px": index !== len - 1
            })}
            onClick={() => this.handleTahSwitch(l)}
          >
            {l.text}
          </View>
        ))}
      </View>
    )
  }
  handleWikiScrollChange = (item: IWikiScroll) => {
    const { curWikiScroll } = this.state
    if (curWikiScroll !== item.selector) {
      this.setState({
        curWikiScroll: item.selector
      })
    }
    Taro.pageScrollTo({
      scrollTop: item.scrollTop
    })
  }
  /** 艺考百科 */
  renderWiki = () => {
    const { curWikiScroll, wikiScrolls, content } = this.state
    return (
      <View className="mt-20px">
        {/* 滚动锚点 */}
        <Sticky>
          <View className="h-75px  box-border bg-hex-fff">
            <ScrollView scrollX scrollWithAnimation className="whitespace-nowrap">
              {wikiScrolls.map(l => (
                <View
                  key={l.selector}
                  className={clsx(styles["wiki-scroll-item"], {
                    [styles["active"]]: curWikiScroll === l.selector
                  })}
                  onClick={() => this.handleWikiScrollChange(l)}
                >
                  {l.text}
                </View>
              ))}
            </ScrollView>
          </View>
        </Sticky>
        {/* 章节内容 */}
        <View className="px-30px pb-40px bg-hex-fff ">
          {/* 大章节item for loop*/}
          {content.map(l => (
            <View className="pt-32px" key={l.menuId}>
              <View
                className="yahei-bold font-bold text-32px text-hex-2c2c35 mb-35px"
                id={l.selector}
              >
                {l.menuName}
              </View>
              <View className="flex flex-col">
                {/* 小章节item for loop */}
                {l.childs &&
                  l.childs.length > 0 &&
                  l.childs.map((child, index) => (
                    <View
                      className={clsx(
                        "rounded-10px bg-hex-fff border border-solid border-hex-eee py-24px px-28px",
                        {
                          "mb-24px": index !== l.childs.length - 1
                        }
                      )}
                      key={child.id}
                    >
                      <View className="yahei font-normal text-30px text-hex-2c2c35 mb-13px">
                        {child.name}
                      </View>
                      <View className="yahei font-normal text-26px text-hex-666 leading-40px">
                        {child.content}
                      </View>
                      <Navigator hoverClass="none" url={child.url} className="mt-33px">
                        <Text className="yahei font-normal text-24px text-hex-b8b8bf">
                          查看详情
                        </Text>
                        <ArrowRight
                          color="#b8b8bf"
                          style={{
                            fontSize: arrowSize
                          }}
                        />
                      </Navigator>
                    </View>
                  ))}
              </View>
            </View>
          ))}
        </View>
      </View>
    )
  }
  render(): React.ReactNode {
    const { wikiScrolls } = this.state
    // 需要保证后台必须返回数据
    if (!wikiScrolls || wikiScrolls.length === 0) return null
    return (
      <GpContainer>
        <View>
          {/* 顶部背景图 */}
          {this.renderBanner()}
          {/* tab切换 */}
          {this.renderTabSwitch()}
          {this.renderWiki()}
          {/* 快捷导航 */}
          {this.renderJumpNavs()}
          {/* 当前位置 */}
          <GpCurrentPort ports={ports} />
        </View>
        {/* 底部导航 */}
        <GpTabbar />
      </GpContainer>
    )
  }
}
export default ColumnPage
